<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" :label-col="labelCol" :wrapper-col="wrapperCol" labelAlign="left" :form="form">
          <a-row :gutter="48">

            <template v-if="!advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="模糊搜索">
                  <a-input  placeholder="" v-model="search" />
                </a-form-item>
              </a-col>
            </template>

            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="补丁编号:">
                  <a-input placeholder="请输入" v-decorator="['patchNo']"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="补丁描述:">
                  <a-input placeholder="" v-decorator="['abs']"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="危险等级:">
                  <a-select  placeholder="请选择" v-decorator="['dangerLv']">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option v-for="item in DangerLevel" :value="item.value">{{item.label}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="操作系统:">
                  <a-select  placeholder="请选择" v-decorator="['adaptationOs']">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option v-for="item in Ostype" :value="item.value">{{item.label}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="补丁类型:">
                  <a-select  placeholder="请选择" v-decorator="['patchTypes']">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option v-for="item in PatchType" :value="item.value">{{item.label}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="补丁分组:">
                  <TreeSelect
                    v-decorator="['patchGroupId']"
                    :tree-data="origintreedata"
                  >
                  </TreeSelect>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="正式标记:">
                  <a-select  placeholder="请选择" v-decorator="['isOfficialMark']">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option v-for="item in MarkType" :value="item.value">{{item.label}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="发布时间:">
                  <a-date-picker  v-decorator="['publishingTime']" style="width: 100%;"/>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
                  <span
                    class="table-page-search-submitButtons"
                    :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
                  >
                    <a-button type="primary" @click="seachlist()">查询</a-button>
                    <a-button style="margin-left: 8px" @click="resetform()">重置</a-button>

                    <a @click="toggleAdvanced" style="margin-left: 8px">
                      {{ advanced ? '收起' : '展开' }}
                      <a-icon :type="advanced ? 'up' : 'down'" />
                    </a>
                  </span>
            </a-col>
          </a-row>
          <a-row style="margin-top: 20px;margin-bottom: 20px;">
            <a-button type="primary" @click="showdetail()">查看详情</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="setgroup()">设置补丁组</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="setzhengshi()">设置正式</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="setpatch()">设置自动转正</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="setblack()">设置黑名单</a-button>
            <a-button type="primary" style="margin-left: 15px" @click="removelib()">删除</a-button>
          </a-row>
        </a-form>
      </div>

      <a-row>
        <a-table :columns="columns" :data-source="data" :row-selection="rowSelection" :pagination="tablepagination" @change="tablechange">
          <template slot="expandedRowRender" slot-scope="record" style="margin: 0">
            补丁简述: {{record.abs}}
            <br/>
            <br/>
            补丁描述(中文): {{record.absCn}}
            <br/>
            <br/>
            对应CVE漏洞编号: {{record.cveId}}
            <br/>
            <br/>
            漏洞简述: {{record.cveSummary}}
            <br/>
            <br/>
            影响软件:
            <br/>
            <span v-for="item in JSON.parse(record.cveAffectPackages)">
            {{item.name}} 修复版本:{{item.fixedIn}}
            <br/>
          </span>
          </template>
          <template slot="dangerLv" slot-scope="text, record">
            <a-tag v-if="text == 0" color="green">{{DangerLevelMap[text.toString()]}}</a-tag>
            <a-tag v-if="text == 1" color="blue">{{DangerLevelMap[text.toString()]}}</a-tag>
            <a-tag v-if="text == 2" color="red">{{DangerLevelMap[text.toString()]}}</a-tag>
          </template>
          <template slot="adaptationOs" slot-scope="text, record">
            {{OstypeMap[text.toString()]}}
          </template>
          <template slot="patchTypes" slot-scope="text, record">
            {{text?PatchTypeMap[text.toString()]:''}}
          </template>
          <template slot="isOfficialMark" slot-scope="text, record">
            <a-tag v-if="text == 1" color="green">{{MarkTypeMap[text.toString()]}}</a-tag>
            <a-tag v-if="text == 0" color="red">{{MarkTypeMap[text.toString()]}}</a-tag>
          </template>
          <template slot="patchSize" slot-scope="text, record">
            {{text?text+'KB':''}}
          </template>
          <template slot="updateTime" slot-scope="text, record">
            {{text?text.replace('T',' '):''}}
          </template>
          <template slot="publishingTime" slot-scope="text, record">
            {{text?text.replace('T',' '):''}}
          </template>
        </a-table>
      </a-row>
    </a-card>
    <Detailmodal ref="detailmodal"></Detailmodal>
    <Mymodal ref="mymodal"></Mymodal>
  </page-header-wrapper>
</template>

<script>
  import Detailmodal from '@/components/mycomp/detailmodal'
  import Mymodal from '@/components/mycomp/mymodal.vue'
  import {getpatchliblist,getpatchById,setOfficial,setBlack,deletepatch,getpatchgrouplist,setpacthGroup,setautozs} from '@/api/patch'
  import {DangerLevel,DangerLevelMap,Ostype,OstypeMap,PatchType,PatchTypeMap,MarkType,MarkTypeMap,TrueFalse} from '../../utils/constant'
  import TreeSelect from 'ant-design-vue/es/tree-select'
  import { setassetsTest } from '@/api/assets'
  export default {
    name: "library",
    components: { Detailmodal,Mymodal,TreeSelect },
    data(){
      return{
        TrueFalse,
        MarkType,
        MarkTypeMap,
        PatchType,
        PatchTypeMap,
        DangerLevel,
        DangerLevelMap,
        Ostype,
        OstypeMap,
        form:this.$form.createForm(this, { name: 'pacthlib' }),
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 },
        },
        advanced:false,
        rowSelection:{
          onChange: (selectedRowKeys, selectedRows) => {
            this.selectarray = selectedRows
            document.getElementById('app').style.transform = `scale(1)`
            document.getElementById('app').style.transformOrigin = `0 0`
            document.getElementById('app').style.height = `100%`
            setTimeout(()=>{
              var scale = (window.innerWidth-20)/1900
              document.getElementById('app').style.transform = `scale(${scale})`
              document.getElementById('app').style.transformOrigin = `0 0`
              document.getElementById('app').style.height = `${100/scale}%`
            },0)
          },
          onSelect: (record, selected, selectedRows) => {
          },
          onSelectAll: (selected, selectedRows, changeRows) => {
          },
        },
        tablepagination:{
          showTotal:(total, range) => {return `共搜索到${total}条数据`},
          current:1,
          total:0
        },
        columns:[
          {
            title:'补丁名称',
            key:'cveTitle',
            dataIndex: 'cveTitle',
            width: 200,
          },
          {
            title:'补丁编号',
            key:'patchNo',
            dataIndex: 'patchNo',
          },
          {
            title:'危险等级',
            key:'dangerLv',
            dataIndex: 'dangerLv',
            scopedSlots: { customRender: 'dangerLv' },
            width: 100
          },
          {
            title:'安全评分',
            key:'cveCvss3Score',
            dataIndex: 'cveCvss3Score',
            width: 100
          },

          {
            title:'适用操作系统',
            key:'adaptationOs',
            dataIndex: 'adaptationOs',
            scopedSlots: { customRender: 'adaptationOs' },
            width: 140
          },
          {
            title:'补丁类型',
            key:'patchTypes',
            dataIndex: 'patchTypes',
            scopedSlots: { customRender: 'patchTypes' },
            width: 100
          },
          {
            title:'补丁分组',
            key:'patchGroupName',
            dataIndex: 'patchGroupName',
            width: 100
          },
          {
            title:'正式标记',
            key:'isOfficialMark',
            dataIndex: 'isOfficialMark',
            scopedSlots: { customRender: 'isOfficialMark' },
            width: 100
          },
          {
            title:'补丁大小',
            key:'patchSize',
            dataIndex: 'patchSize',
            scopedSlots: { customRender: 'patchSize' },
            width: 100
          },
          {
            title:'发布厂商',
            key:'publisher',
            dataIndex: 'publisher',
            width: 100
          },
          {
            title:'更新时间',
            key:'updateTime',
            dataIndex: 'updateTime',
            width:120,
            scopedSlots: { customRender: 'updateTime' },
          },
          {
            title:'发布时间',
            key:'publishingTime',
            dataIndex: 'publishingTime',
            width:120,
            scopedSlots: { customRender: 'publishingTime' },
          }
        ],
        data:[],
        search:'',
        selectarray:null,
        treedata:[],
        origintreedata:[]
      }
    },
    mounted() {
      this.getliblist()
      this.getpatchgroup()
    },
    methods:{
      seachlist(){
        this.tablepagination.current=1;
        this.getliblist()
      },
      tablechange(pagination){
        this.tablepagination = pagination
        this.getliblist()
      },
      trim(str) {
        str = str.match(/\S+(?:\s+\S+)*/);
        return str ? str[0] : '';
      },
      setgroup(){
        if(!this.selectarray || this.selectarray.length == 0){
          this.$message.info('请先选择一条数据')
          return
        }
        let id = this.getids()
        let modalinfo = {
          title:'设置补丁组',
          list:[
            {name:'groupIds',label:'补丁组',require:true,type:'multitree',errortip:'补丁组',treedata:this.treedata},
          ],
          ok:this.setgroupokfun.bind(this),
          moreinfo:{
            ids:id
          }
        }
        this.$refs.mymodal.showmodal(modalinfo)
      },
      setgroupokfun(params){
        params.groupIds = params.groupIds.join(',')
        setpacthGroup(params).then(res=>{
          this.$message.success('操作成功')
          this.getliblist()
        })
      },

      getpatchgroup(){
        getpatchgrouplist({a:0}).then(res=>{
          this.origintreedata = this.transtotree(res.data)
          this.treedata = this.origintreedata[0].children
        })
      },
      transtotree(list){
        let arry = []
        for(let i in list){
          let json = {}
          json.title = list[i].name
          json.key = list[i].id
          json.value = list[i].id
          if(list[i].childNode){
            json.children = this.transtotree(list[i].childNode)
          }
          arry.push(json)
        }
        return arry
      },
      showdetail(){
        if(!this.selectarray || this.selectarray.length == 0){
          this.$message.info('请先选择一条数据')
          return
        }
        if(this.selectarray && this.selectarray.length >1){
          this.$message.info('此操作只支持一条数据')
          return
        }

        let item = this.selectarray[0]
        getpatchById({id:item.id}).then(res=>{
          let modalinfo = {
            title:'详情',
            list:[
              {label:'补丁编号',value:res.data.patchNo},
              {label:'危险等级',value:res.data.dangerLv?DangerLevelMap[res.data.dangerLv]:''},
              {label:'适用操作系统',value:res.data.adaptationOs?OstypeMap[res.data.adaptationOs]:''},
              {label:'补丁类型',value:res.data.patchTypes?PatchTypeMap[res.data.patchTypes]:''},
              {label:'补丁分组',value:res.data.patchGroupName},
              {label:'正式标记',value:res.data.isOfficialMark == 1?'是':'否'},
              {label:'发布厂商',value:res.data.publisher},
              {label:'更新时间',value:res.data.updateTime?res.data.updateTime.replace('T',' '):''},
              {label:'发布时间',value:res.data.publisher?res.data.publisher.replace('T',' '):''},
              {label:'补丁简述',value:res.data.abs},
            ],
          }
          this.$refs.detailmodal.showmodal(modalinfo)
        })

      },
      setzhengshi(){
        if(!this.selectarray || this.selectarray.length == 0){
          this.$message.info('请先选择一条数据')
          return
        }
        let id = this.getids()
        let modalinfo = {
          title:'设置正式',
          list:[
            {name:'isOfficialMark',require:true,label:'设置正式',type:'select',selectdata:this.TrueFalse,errortip:'请选择'},
          ],
          ok:this.setzhengshipok.bind(this),
          moreinfo:{
            id:id
          }
        }
        this.$refs.mymodal.showmodal(modalinfo)
      },

      setpatch(){
        if(!this.selectarray || this.selectarray.length == 0){
          this.$message.info('请先选择一条数据')
          return
        }
        let id = this.getids()
        let modalinfo = {
          title:'补丁自动转正规则配置',
          list:[
            {name:'isAutoOfficialMark',require:true,label:'是否开启补丁自动转正',type:'select',selectdata:this.TrueFalse,errortip:'请选择'},
            {name:'autoOfficialHour',require:true,label:'补丁更新规则',type:'pacthrule',value:'72'},
          ],
          ok:this.setpacthok.bind(this),
          moreinfo:{
            id:id
          }
        }
        this.$refs.mymodal.showmodal(modalinfo)
      },
      setpacthok(params){
        setautozs(params).then(res=>{
          this.$message.success('操作成功')
          this.getliblist()
        })
      },

      setzhengshipok(params){
        if(params.isOfficialMark == '1'){
          let content = ''
          let ids = params.id.split(',')
          for(let i in ids){
            let data = this.data.find(item=>{
              return item.id == ids[i]
            })
            content += (data.patchNo + '\r\n')
          }
          this.$confirm({
            title: '是否将下列选中的补丁设置为正式补丁',
            content: content,
            class:'pre',
            onOk:()=> {
              setOfficial(params).then(res=>{
                this.$message.success('操作成功')
                this.getliblist()
              })
            },
            onCancel() {},
          });
        }else{
          setOfficial(params).then(res=>{
            this.$message.success('操作成功')
            this.getliblist()
          })
        }

      },

      removelib(){
        if(!this.selectarray || this.selectarray.length == 0){
          this.$message.info('请先选择一条数据')
          return
        }
        let id = this.getids()

        this.$confirm({
          title: '是否确认删除数据?',
          okText: '是',
          okType: 'danger',
          cancelText: '否',
          onOk:()=> {
            deletepatch({id:id}).then(res=>{
              this.$message.success('操作成功')
              this.getliblist()
            })
          }
        });
      },

      setblack(){
        if(!this.selectarray || this.selectarray.length == 0){
          this.$message.info('请先选择一条数据')
          return
        }
        let id = this.getids()
        let modalinfo = {
          title:'设置黑名单',
          list:[
            {name:'blacklistCause',label:'拉黑原因',type:'input'},
          ],
          ok:this.setblackok.bind(this),
          moreinfo:{
            ids:id,
            isBlacklist:1
          }
        }
        this.$refs.mymodal.showmodal(modalinfo)
      },
      setblackok(params){
        let content = ''
        let ids = params.ids.split(',')
        for(let i in ids){
          let data = this.data.find(item=>{
            return item.id == ids[i]
          })
          content +=  (data.patchNo + '\r\n')
        }

        this.$confirm({
          title: '是否将下列选中的补丁加入黑名单',
          content: content,
          class:'pre',
          onOk:()=> {
            setBlack(params).then(res=>{
              this.$message.success('设置成功')
              this.getliblist()
            })
          },
          onCancel() {},
        });


      },

      resetform(){
        this.form.resetFields()
        this.search = ''
      },
      getliblist(){
        let params = {}
        params.pageNo = this.tablepagination.current
        params.pageSize = 10
        params.isBlacklist = 0
        if(this.advanced){
          Object.assign(params,this.form.getFieldsValue())
        }else{
          params.search = this.trim(this.search)
        }
        getpatchliblist(params).then(res=>{
          let record = res.data.records
          for(let i in record){
            record[i].key =record[i].id
          }
          this.data = record
          this.tablepagination.total = res.data.total
        })
      },
      getids(){
        let arry = []
        for(let i in this.selectarray){
          arry.push(this.selectarray[i].id)
        }
        let id = arry.join(',')
        return id
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
    }
  }
</script>

<style lang="less" scoped>
  @import "~ant-design-vue/es/tree-select/style/index.less";
</style>